/**
 * 加载界面
 */
import GViewBase from "../../../Core/GView/GViewBase";
import { Wechat } from "../../../Core/Platform/wechat/wechat";
import { tyqSDK } from "../../../tyq/tyq-sdk";
import { L } from '../../Common/Language';
import { VIEW_ID } from "../../Common/UI";
import GameMgr from '../../Logic/GameMgr';
import SdkMgr from "../../Logic/SdkMgr";
import { JXDef } from './../../../conventions/JXCommon';
import { WinPage } from './../../../Core/CoreDefine';
import { GCtrl } from './../../../Core/GCtrl';
import { UIMgr } from './../../../Core/Manager/UIMgr';
import { Res } from './../../Common/UIResources';
import { JXLocales } from './../../Common/Zh';

const { ccclass, property } = cc._decorator;

interface LoadConfigRaw {
    start?: number;
    loginRaw?: number;
    loginStatic?: number;
    loginAciton?: number;
    gameRaw?: number;
    gameStatic?: number
    otherStatic?: number;
    userData?: number;
}

// 加载权重
const PROCESS_CONFIGS = {
    newAccountLogin: {
        start: 0.5,
        loginRaw: 0.1,
        loginStatic: 0.1,
        loginAciton: 0.1,
        gameRaw: 0.1,
        gameStatic: 0.05,
        userData: 0.05,
    } as LoadConfigRaw,
    oldLogin: {
        start: 0.5,
        loginRaw: 0.25,
        loginStatic: 0.25
    } as LoadConfigRaw,
    oldGame: {
        gameRaw: 0.3,
        gameStatic: 0.4,
        userData: 0.3,
    } as LoadConfigRaw,
}


@ccclass
export default class LoadCtrl extends GViewBase {
    /**加载进度文本 */
    @property(cc.Label) progressLabel: cc.Label = null;
    /**加载进度条 */
    @property(cc.ProgressBar) progressBar: cc.ProgressBar = null;
    @property(cc.Node) lightNode: cc.Node = null;
    @property(cc.Prefab) privacypolicy: cc.Prefab = null;
    @property(cc.Prefab) verifyRealName: cc.Prefab = null;
    @property(cc.Boolean) isPrivacy: boolean = true;
    @property(cc.Boolean) isVerifyRealName: boolean = true;
    // 已使用进度
    public useProgress: number = 0;
    // 当前进度
    public curProgress: number = 0;
    protected _curLoadConfig: LoadConfigRaw = null;
    private loadNum: number = 0;

    onGLoad() {

        if (this.progressBar) this.progressBar.progress = 0;
        if (this.progressLabel) this.progressLabel.string = "";

        if (SdkMgr.ins.isWechat()) {
            Wechat.showShareMenu();
        }
        tyqSDK.init(() => {
            this.Privacypolicy();
        });

    }



    public VerifyRealName() {
        if (!this.isVerifyRealName) {
            this.startLoad();
            return;
        }
        tyqSDK.showVerifyRealName(this.node, () => {
            this.startLoad();
        });
    }


    public Privacypolicy() {
        if (!this.isPrivacy) {
            this.VerifyRealName();
            return;
        }
        tyqSDK.showVerifyPrivacypolicy(this.node, () => {
            this.VerifyRealName();
        })
    }

    startLoad() {
        this._curLoadConfig = PROCESS_CONFIGS.oldLogin;
        this.useProgress = this._curLoadConfig.start;
        this.curProgress = this._curLoadConfig.loginRaw;
        /**分包加载 */
        this.loadPackage();
    }

    protected preLoadGameStart() {
        this.setLoadText(L(JXLocales.load.assetLoad));
        this.setLoadProgress(this.useProgress);
        // 预加载不希望用的时候异步的预制件
        GCtrl.preLoadRawAssets((curIndex: number, total: number, asset) => {
            this.setLoadText(L(JXLocales.load.process, curIndex, total));
            this.setLoadProgress(this.useProgress + curIndex / total * this.curProgress);
        }, () => {
            this.loadloginStatic();
        },
            ...Object.keys(Res.material).map((v, k) => { return { type: cc.Material, path: Res.material[v] } }),
            { type: cc.Prefab, path: Res.prefab.item.topUiItem },
            { type: cc.Prefab, path: Res.prefab.vw.tip.toast },

        );
    }

    protected preLoadGameScene() {
        this.setLoadText(L(JXLocales.load.assetLoad));
        this.useProgress += this.curProgress;
        this.curProgress = this._curLoadConfig.gameRaw;
        // 预加载不希望用的时候异步的预制件
        GCtrl.preLoadRawAssets((curIndex: number, total: number, asset) => {
            this.setLoadText(L(JXLocales.load.process, curIndex, total));
            this.setLoadProgress(this.useProgress + curIndex / total * this.curProgress);
        }, () => {
            this.loadGameStatic();
        },
            { type: cc.SpriteFrame, path: Res.texture.single },
            { type: cc.AudioClip, path: Res.audio.main },
            { type: cc.AudioClip, path: Res.audio.btnClick },
            { type: cc.AudioClip, path: Res.audio.battle + "battle_1" },
            { type: cc.AudioClip, path: Res.audio.battle + "battle_2" },
            { type: cc.AudioClip, path: Res.audio.battle + "battle_3" },
            { type: cc.AudioClip, path: Res.audio.battle + "battle_4" },
            { type: cc.AudioClip, path: Res.audio.battle + "battle_5" },
        );
    }


    protected loadloginStatic() {
        this.useProgress += this.curProgress; // 0.5 +0.2; 0.5 + 0.4
        this.curProgress = this._curLoadConfig.loginStatic; //0.5 +0.2 +0.2; 0.5 +0.4 
        GameMgr.initLoginStatic((cur, total) => {
            this.setLoadText(L(JXLocales.load.static, cur, total));
            this.setLoadProgress(this.useProgress + this.curProgress * cur / total)
        }, () => {
            GameMgr.initSimulator();
            GameMgr.initLogicManager();
            //#region 
            GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.loadScene, { msg: '' });//GameMgr.lUserData.checkIsNewUser() ? "新用户" : "老用户"
            this._curLoadConfig = PROCESS_CONFIGS.oldGame;
            this.preLoadGameScene();
        })
    }


    protected loadGameStatic() {
        this.useProgress += this.curProgress;
        this.curProgress = this._curLoadConfig.gameStatic;
        GameMgr.initFristGameStatics((cur, total) => {
            this.setLoadText(L(JXLocales.load.static, cur, total));
            this.setLoadProgress(this.useProgress + cur / total * this.curProgress);
        }, () => {

            this.onInitUserData();
        })
    }

    /** 加载用户数据 */
    public onInitUserData() {
        this.setLoadText(L(JXLocales.load.initUserData));
        this.useProgress += this.curProgress;
        this.curProgress = this._curLoadConfig.userData;
        this.loadHomeCtrl();
        // let tasks = getInitTask((route, resp) => {

    }

    protected loadHomeCtrl() {
        this.setLoadText(L(JXLocales.load.enter_game));
        GameMgr.ins().initGame();

        // 预加载主场景资源：
        GCtrl.preLoadRawAssets(null, () => {
            this.endLoadHomeCtrl();
        },
            { type: cc.Prefab, path: Res.prefab.vw.home.homeCtrl },
            { type: cc.Prefab, path: Res.prefab.vw.home.mainCtrl },
            { type: cc.Prefab, path: Res.prefab.vw.home.chapterPage },
            { type: cc.Prefab, path: Res.prefab.vw.store.storeCtrl },
            { type: cc.Prefab, path: Res.prefab.vw.hero.heroCtrl },
            { type: cc.Prefab, path: Res.prefab.vw.hero.squadCtrl },
            { type: cc.Prefab, path: Res.prefab.vw.home.recruitCtrl },
            { type: cc.Prefab, path: Res.prefab.item.jxItem },
            { type: cc.Prefab, path: Res.prefab.item.heroCardItem },
            { type: cc.Prefab, path: Res.prefab.item.guide_item },
        );
    }

    /**所有数据加载完成进入游戏 */
    protected endLoadHomeCtrl() {
        if (true) {
            UIMgr.showWin(VIEW_ID.home, WinPage.Page0);
            GCtrl.ES.emit(GCtrl.GClientWinOpenEventMsg);
            GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.inGameScene, { msg: '' });//GameMgr.lUserData.checkIsNewUser() ? "新用户" : "老用户"
        } else {
            // SdkMgr.ins.authorize((userInfo: IUserInfo | null) => {
            //     // if (userInfo) {
            //     //     GameMgr.lUserData.nickName = userInfo.nickName;
            //     //     GameMgr.lUserData.avatar = userInfo.avatar;
            //     // } else {
            //     //     GameMgr.lUserData.randName();
            //     // }
            //     GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.inGameScene, { identity: GameMgr.lUserData.checkIsNewUser() ? "新用户" : "老用户" });
            //    
            //    
            // })

        }
    }

    protected setLoadText(text: string) {
        if (!this.progressLabel) return;
        this.progressLabel.string = text;
    }

    protected setLoadProgress(val: number) {
        if (!this.progressBar) return;
        this.progressBar.progress = Math.min(val, 1);
        if (this.lightNode) {
            this.lightNode.x = this.progressBar.totalLength * this.progressBar.progress;
        }
    }

    /**加载分包 */
    loadPackage() {
        this.setLoadText(L(JXLocales.load.loadPackage));
        let keys = Object.keys(JXDef.bundle);
        const str = JXDef.bundle[keys[this.loadNum]];
        console.log("加载分包: ", str);
        cc.assetManager.loadBundle(str, (err: Error, boule: cc.AssetManager.Bundle) => {
            if (err) {
                console.log(str + "分包加载失败");
            }
            this.loadNum++;
            this.setLoadProgress(this.loadNum / keys.length);
            if (this.loadNum < keys.length) {
                this.loadPackage();
            } else {
                this.preLoadGameStart();
            }
        });
    }
}



